#include <stdio.h>
#include "user_list.h"


void main() {
    struct list_head head1, head2;
    struct node_t {
        list_node_t     node;
        unsigned int    value;
    };
    struct node_t node1, node2, node3, node4;
    
    printf("user list test.\n");

    node1.value = 1;
    node2.value = 2;
    node3.value = 3;
    node4.value = 4;

    list_head_init(&head1);
    list_head_init(&head2);

    // list_add_tail() 将节点添加到链表最后面
    list_add_tail(&node1.node, &head1);
    list_add_tail(&node2.node, &head1);
    list_add_tail(&node3.node, &head1);
    // list_add() 将节点添加到链表最前面
    list_add(&node4.node, &head1);

    // list_add(&node3.node, &head2);
    // list_add_tail(&node4.node, &head2);

    // 非安全方式遍历，只用于查询
    printf("for_each_entry list1:\n");
    struct node_t *pNode = NULL;
    list_for_each_entry(pNode, &head1, node) {
        printf("value=%u\n", pNode->value); 
    }

    printf("for_each_entry list2:\n");
    list_for_each_entry(pNode, &head2, node) {
        printf("value=%u\n", pNode->value); 
    }    

    printf("\n");
    printf("head1 is empty? %s\n", list_empty(&head1) ? "yes" : "no");
    printf("head2 is empty? %s\n", list_empty(&head2) ? "yes" : "no");   

    // 安全方式遍历，可以删除节点
    struct node_t *pNode1 = NULL, *pTemp = NULL;
    list_for_each_entry_safe(pNode1, pTemp, &head1, node) {
        if (pNode1->value == 2) {
            printf("value=%u del. from list1.\n", pNode1->value); 
            list_del(&pNode1->node);
        }
    }

    printf("for_each_entry list1:\n");
    struct node_t *pNode2 = NULL;
    list_for_each_entry(pNode2, &head1, node) {
        printf("value=%u\n", pNode2->value); 
    }

    printf("head1 is empty? %s\n", list_empty(&head1) ? "yes" : "no");
    printf("head2 is empty? %s\n", list_empty(&head2) ? "yes" : "no");   

    if (!list_empty(&head2)) {
        list_del(&node2.node);
    }

    printf("head1 is empty? %s\n", list_empty(&head1) ? "yes" : "no");
    printf("head2 is empty? %s\n", list_empty(&head2) ? "yes" : "no"); 

    printf("list test end.\n");

}